<template>
    <van-field
      :class="{'active':focusIdx==config.key}"
      v-model="config.value"
      :label="config.label"
      :required="config.must"
      :readonly="config.readonly"
      :disabled="config.disabled"
      :placeholder="config.placeholder"
      @focus="onFocus"
      @blur="onBlur"
    >
      <van-button slot="button" size="small" type="primary" :disabled="btnDisabled" @click="getCode">{{btnText}}</van-button>
    </van-field>
</template>

<script>
import $ from 'jquery';
export default {
  data() {
    return {
      focusIdx: null,
      btnText: '发送验证码',
      btnDisabled: false
    };
  },
  props: ['config'],
  methods: {
    onFocus() {
      this.focusIdx = this.config.key;
    },
    onBlur() {
      this.focusIdx = null;
    },
    getCode() {
      if (this.$store.state.UserInfo.Phone == '') {
        this.$toast('请先输入手机号');
      } else if (/^1[345678]\d{9}$/.test(this.$store.state.UserInfo.Phone) == false) {
        this.$toast('请输入正确的手机号');
      } else {
        var that = this;
        that.btnDisabled = true;
        $.ajax({
          type: 'GET',
          url: `${that.baseUrl}/api/user/getVerifyVode/${that.$store.state.UserInfo.Phone}/${that.$store.state.UserInfo.ST}`,
          success: function(res) {
            if (res.State) {
              let second = 120;
              that.btnText = '还剩' + second + '秒';
              var timer = setInterval(() => {
                second--;
                if (second > 0) {
                  that.btnText = '还剩' + second + '秒';
                } else {
                  clearInterval(timer);
                  that.btnDisabled = false;
                  that.btnText = '发送验证码';
                  second = 120;
                }
              }, 1000);
            } else {
              that.$toast(res.Message);
            }
          }
        });
      }
    }
  },
  watch: {
    'config.value': function(val, oldVal) {
      this.$store.commit('SET_VERIFYVODE', val);
    }
  }
};
</script>

<style>
</style>
